package com.cw.controller;

import com.cw.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
public class SessionController {
    //设置Cookie
    @GetMapping("/c1")
    public Result cookie1(HttpServletResponse response) {
        response.addCookie(new Cookie("lzx", "我是小皇帝"));
        return Result.success();
    }

    //获取Cookie
    @GetMapping("/c2")
    public Result cookie2(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies(); //获取所有的Cookie
        for (Cookie cookie :
                cookies) {
            if (cookie.getName().equals("lzx")) {
                System.out.println("lzx:" + cookie.getValue());
            }
        }
        return Result.success();
    }

    //往HttpSession存储值
    @GetMapping("/s1")
    public Result session1(HttpSession session) {
        log.info("HttpSession-s1:{}",session.hashCode());
        session.setAttribute("lzx","king"); //往session中存储数据
        return Result.success();
    }

    //从HttpSession获取值
    @GetMapping("/s2")
    public Result session2(HttpServletRequest request) {
        HttpSession session = request.getSession();
        log.info("HttpSession-s1:{}",session.hashCode());
        Object attribute = session.getAttribute("lzx");//从session中获取数值
        log.info("lzx:{}",attribute);
        return Result.success();
    }

}
